import es
import popuplib2

__all__ = ["RaceGroupPopup"]

class RaceGroupPopup(object):
    """
    This object will be used to create and store a single popup instance. This
    popup will be used to create the list of races (in order) that recide within
    this group, and then list any further group directory.
    """
    def __init__(self, groupObject):
        """
        Default constructor, ensure that the popup object is created and default
        attributes assigned.
        
        @param RaceGroup groupObject The object of the group this popup is for.
        """
        self.groupObj = groupObject
        self.popup = popuplib2.PersonalMenu(self._build)
        self.popup.title = "WarCraft Python - Change Race"
        self.popup.description = "Select an option to change your race"
        self.popup.menuselect = self._callback
        self.popup.call_special = True
        
    def _build(self, userid, popupInstance):
        """
        Executed before this object's popup is sent to the user, assume that we
        need to add all the user's current races to the race list. If the user
        is currently playing that race, then append an asterix to denote usage.

        @private
        @param int userid The ID of the user this popup is being built for
        @param popuplib2.UserPopup The Popup instance that this user will use
        """
        from wcs.libs.players import players
        from wcs.libs.races import races
        from wcs.libs.common import isUseridAuthorized
        
        player = players[userid]
        if player is None:
            return None
        race = player[player.currentRace]
        for name in sorted(self.groupObj.groups, cmp=self.groupObj.sortGroups):
            groupObject = self.groupObj.groups[name]
            if groupObject.authorization is None:
                popupInstance.add(groupObject, "> %s" % name)
            else:
                results = isUseridAuthorized(userid, groupObject.authorization)
                if results:
                    popupInstance.add(groupObject, "> %s" % name, results)
        for name in sorted(self.groupObj.raceOrder, 
                           cmp=self.groupObj.sortRaces):
            raceObject = races[name]
            visualName = name
            if raceObject.minLevel and player.level < raceObject.minLevel:
                visualName += " (Min Level Req: %s)" % raceObject.minLevel
            elif raceObject.teamLimit:
                currentTeam = es.getplayerteam(userid)
                teamRaces = []
                for player in es.getUseridList():
                    if es.getplayerteam(player) != currentTeam:
                        continue
                    if player == userid:
                        continue
                    teamRaces.append(players[player].currentRace)
                if teamRaces.count(name) >= raceObject.teamLimit:
                    visualName += " (Team Limit: %s)" % raceObject.teamLimit
            elif raceObject.team:
                currentTeam = es.getplayerteam(userid)
                strTeam = {2:"T", 3:"CT"}[raceObject.team]
                if currentTeam != raceObject.team:
                    visualName += " (Team Filter: %s)" % strTeam
            elif raceObject.steamid:
                if es.getplayersteamid(userid) not in raceObject.steamid:
                    continue # Do not show the race on the menu
            elif raceObject.authorization:
                if isUseridAuthorized(userid, raceObject.authorization):
                    continue # Do not show the race on the menu
                    
            elif name == race.raceName:
                visualName += " (*)"
            popupInstance.add(raceObject, visualName)

    def _callback(self, args):
        """
        Executed when a user has pressed a menu button. If the user selects back
        then send them to the previous page; otherwise, send them to the race
        popup menu that they selected.

        @private
        @param tuple args All arguments passed by popuplib
        """
        if args["raw_choice"] == 10:
            if self.groupObj.parent is not None:
                return self.groupObj.parent.popup
            return None
        if args["raw_choice"] == 8 or args["raw_choice"] == 9:
            return
        args["choice"].lastMenu = self.groupObj
        if hasattr(args["choice"], "popup"):
            return args["choice"].popup
        return args["choice"].racePopup